import path from 'path';
import { defineConfig, loadEnv } from 'vite';
import setupVitePlugins, { parseEnv } from './build/plugins';
import { visualizer } from 'rollup-plugin-visualizer';

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
  // const isBuild = command === 'build';
  const root = process.cwd();
  const env = parseEnv(loadEnv(mode, root));

  return {
    plugins: [...setupVitePlugins(env.VITE_DEV_MOCK), visualizer({ open: true })],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
        '#': path.resolve(__dirname, './src/types'),
      },
    },
    server: {
      host: true,
      proxy: {
        '/api': {
          // 以/api访问转化为target
          target: env.VITE_API_URL,
          // 跨域请求携带cookie
          changeOrigin: true,
        },
      },
    },
    build: {
      emptyOutDir: true,
      rollupOptions: {
        output: {
          manualChunks(id: string) {
            if (id.includes('node_modules')) {
              return id.split('/node_modules/').pop()?.split('/')[0];
            }
          },
        },
      },
    },
  };
});
